import wepy from 'wepy'

export default class extends wepy.mixin {
  methods = {
    goGoodsDetail(id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?id=' + id
      })
    }
  }

  data = {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 20,
    goodsList: [],
    total: 0,
    flag: false,
    isOK: true
  }

  onLoad(options) {
    this.query = options.search || ''
    this.cid = options.id || ''

    console.log(options)

    this.getGoodsList()
  }

  async getGoodsList(fn) {
    this.isOK = false
    let {data: res} = await wepy.get('/goods/search', {
      query: this.query,
      cid: this.cid,
      pagenum: this.pagenum,
      pagesize: this.pagesize
    })

    this.isOK = true
    if(res.meta.status !== 200) {
      return wepy.baseToast()
    }

    this.goodsList = [...this.goodsList, ...res.message.goods]
    this.total = res.message.total
    this.$apply()

    fn && fn()

  }

  onReachBottom() {
    if(!this.isOK) {
      return 
    }

    if(this.pagenum * this.pagesize >= this.total) {
      this.flag = true
      return 
    }
    this.pagenum++
    this.getGoodsList()
  }

  onPullDownRefresh() {
    this.pagenum = 1
    this.pagesize = 20
    this.goodsList = []
    this.tota =  0
    this.flag = false
    this.isOK = true

    this.getGoodsList(function(){
      wepy.stopPullDownRefresh()
    })
  }
}